package com.cyd.product_service.controller;


import com.cyd.product_service.cluster.ClusterService;
import com.cyd.product_service.cluster.consul.ConsulServiceSelector;
import com.cyd.product_service.cluster.loadbalance.WeightedRandomLoadBalance;
import com.cyd.product_service.service.impl.StudentServiceImpl;
import com.cyd.product_service.service.thrift.DataException;
import com.cyd.product_service.service.thrift.StudentService;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TMultiplexedProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class TestController {

    @GetMapping("/getTest")
    public String getOrderList() {
        TTransport transport = null;
        ClusterService service = getStandardService();
        transport = new TFramedTransport(new TSocket(service.getAddress(), service.getPort()));
        System.out.println(service.getAddress() + " ||| " + service.getPort());
        try {
            transport.open();
        } catch (TTransportException e) {
            e.printStackTrace();
        }
        TProtocol protocol = new TBinaryProtocol(transport);
//        TMultiplexedProtocol mpStandard = new TMultiplexedProtocol(protocol, "UnitService");
//        UnitService.Client client = new UnitService.Client(mpStandard);

        TMultiplexedProtocol mpStandard = new TMultiplexedProtocol(protocol, "HelloWorldService");
        StudentService.Client client = new StudentService.Client(mpStandard);

        try {
            System.out.println(client.getStudentByName("1"));
            return "" + client.getStudentByName("2");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "Error Hello Word";
    }

    private ClusterService getStandardService() {
        ConsulServiceSelector selector = new ConsulServiceSelector(
                new WeightedRandomLoadBalance());
        return selector.selectMaster("product-server2");
    }

}
